/*!
    \file    gd32f30x_it.c
    \brief   interrupt service routines

    \version 2017-02-10, V1.0.0, firmware for GD32F30x
    \version 2018-10-10, V1.1.0, firmware for GD32F30x
    \version 2018-12-25, V2.0.0, firmware for GD32F30x
    \version 2020-09-30, V2.1.0, firmware for GD32F30x 
*/

/*
    Copyright (c) 2020, GigaDevice Semiconductor Inc.

    Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this 
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice, 
       this list of conditions and the following disclaimer in the documentation 
       and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors 
       may be used to endorse or promote products derived from this software without 
       specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
OF SUCH DAMAGE.
*/

#include "gd32f30x_it.h"
#include "stdio.h"

#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"

#include "DevicesTime.h"
#include "DevicesQueue.h"
#include "DevicesUart.h"
#include "DevicesLed.h"
#include "DevicesSoftTimer.h"
#include "DevicesRTC.h"

#include "taskMessageSlave.h"
#include "taskSystem.h"

#include "main.h"

/*!
    \brief      this function handles NMI exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void NMI_Handler(void)
{
}

/*!
    \brief      this function handles HardFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void HardFault_Handler(void)
{
//    printf("\n\n\r HardFault_Handler.\n\n");
    /* if Hard Fault exception occurs, go to infinite loop */
    while (1){
    }
}

/*!
    \brief      this function handles MemManage exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void MemManage_Handler(void)
{
    printf("\n\n\r MemManage_Handler.\n\n");
    /* if Memory Manage exception occurs, go to infinite loop */
    while (1){
    }
}

/*!
    \brief      this function handles BusFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void BusFault_Handler(void)
{
    printf("\n\n\r BusFault_Handler.\n\n");
    /* if Bus Fault exception occurs, go to infinite loop */
    while (1){
    }
}

/*!
    \brief      this function handles UsageFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void UsageFault_Handler(void)
{
    printf("\n\n\r UsageFault_Handler.\n\n");
    /* if Usage Fault exception occurs, go to infinite loop */
    while (1){
    }
}

// /*!
//     \brief      this function handles SVC exception
//     \param[in]  none
//     \param[out] none
//     \retval     none
// */
// void SVC_Handler(void)
// {
// }

/*!
    \brief      this function handles DebugMon exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void DebugMon_Handler(void)
{
}

// /*!
//     \brief      this function handles PendSV exception
//     \param[in]  none
//     \param[out] none
//     \retval     none
// */
// void PendSV_Handler(void)
// {
// }

// /*!
//     \brief      this function handles SysTick exception
//     \param[in]  none
//     \param[out] none
//     \retval     none
// */
// void SysTick_Handler(void)
// {
//     delay_decrement();
// }

void vUSART0ReceiveCallback(void)
{
    static uint32_t uiMDANdtrOld = 0;
    uint32_t uiMDANdtrNow = 0;

    while(uiMDANdtrOld != (uiMDANdtrNow = USART0_DMA_READ_LENGTH - dma_transfer_number_get(DMA0, DMA_CH4)))
    {
        if(uiMDANdtrNow < uiMDANdtrOld)
        {
            /* 把一帧数据读取到UART队列缓存里 */
            enumQueuePushDatas(&g_TypeQueueUart0Read, &g_USART0ReadDMABuff[uiMDANdtrOld], USART0_DMA_READ_LENGTH - uiMDANdtrOld);

            uiMDANdtrOld = 0;
        }

        /* 把一帧数据读取到UART队列缓存里 */
        enumQueuePushDatas(&g_TypeQueueUart0Read, &g_USART0ReadDMABuff[uiMDANdtrOld], uiMDANdtrNow - uiMDANdtrOld);

        uiMDANdtrOld = uiMDANdtrNow;
    }
}

void vUSART1ReceiveCallback(void)
{
    static uint32_t uiMDANdtrOld = 0;
    uint32_t uiMDANdtrNow = 0;

    while(uiMDANdtrOld != (uiMDANdtrNow = USART0_DMA_READ_LENGTH - dma_transfer_number_get(DMA0, DMA_CH5)))
    {
        if(uiMDANdtrNow < uiMDANdtrOld)
        {
            /* 把一帧数据读取到UART队列缓存里 */
            enumQueuePushDatas(&g_TypeQueueUart1Read, &g_USART1ReadDMABuff[uiMDANdtrOld], USART1_DMA_READ_LENGTH - uiMDANdtrOld);

            uiMDANdtrOld = 0;
        }

        /* 把一帧数据读取到UART队列缓存里 */
        enumQueuePushDatas(&g_TypeQueueUart1Read, &g_USART1ReadDMABuff[uiMDANdtrOld], uiMDANdtrNow - uiMDANdtrOld);

        uiMDANdtrOld = uiMDANdtrNow;
    }
}

void vUSART2ReceiveCallback(void)
{
    static uint32_t uiMDANdtrOld = 0;
    uint32_t uiMDANdtrNow = 0;

    while(uiMDANdtrOld != (uiMDANdtrNow = USART2_DMA_READ_LENGTH - dma_transfer_number_get(DMA0, DMA_CH2)))
    {
        if(uiMDANdtrNow < uiMDANdtrOld)
        {
            /* 把一帧数据读取到UART队列缓存里 */
            enumQueuePushDatas(&g_TypeQueueUart2Read, &g_USART2ReadDMABuff[uiMDANdtrOld], USART2_DMA_READ_LENGTH - uiMDANdtrOld);
            uiMDANdtrOld = 0;
        }

        /* 把一帧数据读取到UART队列缓存里 */
        enumQueuePushDatas(&g_TypeQueueUart2Read, &g_USART2ReadDMABuff[uiMDANdtrOld], uiMDANdtrNow - uiMDANdtrOld);

        uiMDANdtrOld = uiMDANdtrNow;
    }
}

void vUSART3ReceiveCallback(void)
{
    static uint32_t uiMDANdtrOld = 0;
    uint32_t uiMDANdtrNow = 0;

    while(uiMDANdtrOld != (uiMDANdtrNow = USART3_DMA_READ_LENGTH - dma_transfer_number_get(DMA1, DMA_CH2)))
    {
        if(uiMDANdtrNow < uiMDANdtrOld)
        {
            /* 把一帧数据读取到UART队列缓存里 */
            enumQueuePushDatas(&g_TypeQueueUart3Read, &g_USART3ReadDMABuff[uiMDANdtrOld], USART3_DMA_READ_LENGTH - uiMDANdtrOld);
            uiMDANdtrOld = 0;
        }

        /* 把一帧数据读取到UART队列缓存里 */
        enumQueuePushDatas(&g_TypeQueueUart3Read, &g_USART3ReadDMABuff[uiMDANdtrOld], uiMDANdtrNow - uiMDANdtrOld);

        uiMDANdtrOld = uiMDANdtrNow;
    }
}

/*!
    \brief      this function handles USART interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void USART0_IRQHandler(void)
{
    volatile static uint32_t uiMDANdtrNow = 0, uiMDANdtrOld = 0;

    if(usart_interrupt_flag_get(USART0, USART_INT_FLAG_IDLE) != RESET)
    {
        vUSART0ReceiveCallback();

        /* 软件先读USART_STAT0，再读USART_DATA可清除空闲中断标志 */
        usart_data_receive(USART0);
        usart_interrupt_flag_clear(USART0, USART_INT_FLAG_IDLE);

//        /* 给出信号量，以启动任务执行解析 */
//        xTaskNotifyFromISR(g_TaskMessageSlaveHand, 0x01, eSetBits, NULL);
    }
    else if(usart_flag_get(USART0, USART_FLAG_ORERR) != RESET)
    {
        /* 软件先读USART_STAT0，再读USART_DATA可清除错误中断标志 */
        usart_data_receive(USART0);

        /* 重新初始化 */
        vUart0Init();
    }
    /* 错误中断 */
    else if((usart_flag_get(USART0, USART_FLAG_NERR) != RESET) ||
            (usart_flag_get(USART0, USART_FLAG_FERR) != RESET) ||
            (usart_flag_get(USART0, USART_FLAG_PERR) != RESET))
    {
        usart_flag_clear(USART0, USART_FLAG_CTS);
        usart_flag_clear(USART0, USART_FLAG_LBD);
        usart_flag_clear(USART0, USART_FLAG_TC);
        usart_flag_clear(USART0, USART_FLAG_RBNE);
        usart_flag_clear(USART0, USART_FLAG_EB);
        usart_flag_clear(USART0, USART_FLAG_RT);

        usart_interrupt_flag_clear(USART0, USART_INT_FLAG_CTS);
        usart_interrupt_flag_clear(USART0, USART_INT_FLAG_LBD);
        usart_interrupt_flag_clear(USART0, USART_INT_FLAG_TC);
        usart_interrupt_flag_clear(USART0, USART_INT_FLAG_RBNE);
        usart_interrupt_flag_clear(USART0, USART_INT_FLAG_EB);
        usart_interrupt_flag_clear(USART0, USART_INT_FLAG_RT);

        /* 软件先读USART_STAT0，再读USART_DATA可清除错误xxx中断标志 */
        usart_data_receive(USART0);
    }
}

/*!
    \brief      this function handles DMA interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void DMA0_Channel4_IRQHandler(void)
{
    if(dma_interrupt_flag_get(DMA0, DMA_CH4, DMA_INT_FTF) != RESET)
    {
        vUSART0ReceiveCallback();

        dma_interrupt_flag_clear(DMA0, DMA_CH4, DMA_INT_FTF);
    }
    else if(dma_interrupt_flag_get(DMA0, DMA_CH4, DMA_INT_HTF) != RESET)
    {
        vUSART0ReceiveCallback();

        dma_interrupt_flag_clear(DMA0, DMA_CH4, DMA_INT_HTF);
    }
}

/*!
    \brief      this function handles USART interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void USART1_IRQHandler(void)
{
    volatile static uint32_t uiMDANdtrNow = 0, uiMDANdtrOld = 0;

    if(usart_interrupt_flag_get(USART1, USART_INT_FLAG_IDLE) != RESET)
    {
        vUSART1ReceiveCallback();

        /* 软件先读USART_STAT0，再读USART_DATA可清除空闲中断标志 */
        usart_data_receive(USART1);
        usart_interrupt_flag_clear(USART1, USART_INT_FLAG_IDLE);

//        /* 给出信号量，以启动任务执行解析 */
//        xTaskNotifyFromISR(g_TaskMessageSlaveHand, 0x02, eSetBits, NULL);
    }
    else if(usart_flag_get(USART1, USART_FLAG_ORERR) != RESET)
    {
        /* 软件先读USART_STAT0，再读USART_DATA可清除错误中断标志 */
        usart_data_receive(USART1);

        /* 重新初始化 */
        vUart1Init();
    }
    /* 错误中断 */
    else if((usart_flag_get(USART1, USART_FLAG_NERR) != RESET) ||
            (usart_flag_get(USART1, USART_FLAG_FERR) != RESET) ||
            (usart_flag_get(USART1, USART_FLAG_PERR) != RESET))
    {
        usart_flag_clear(USART1, USART_FLAG_CTS);
        usart_flag_clear(USART1, USART_FLAG_LBD);
        usart_flag_clear(USART1, USART_FLAG_TC);
        usart_flag_clear(USART1, USART_FLAG_RBNE);
        usart_flag_clear(USART1, USART_FLAG_EB);
        usart_flag_clear(USART1, USART_FLAG_RT);

        usart_interrupt_flag_clear(USART1, USART_INT_FLAG_CTS);
        usart_interrupt_flag_clear(USART1, USART_INT_FLAG_LBD);
        usart_interrupt_flag_clear(USART1, USART_INT_FLAG_TC);
        usart_interrupt_flag_clear(USART1, USART_INT_FLAG_RBNE);
        usart_interrupt_flag_clear(USART1, USART_INT_FLAG_EB);
        usart_interrupt_flag_clear(USART1, USART_INT_FLAG_RT);

        /* 软件先读USART_STAT0，再读USART_DATA可清除错误xxx中断标志 */
        usart_data_receive(USART1);
    }
}

/*!
    \brief      this function handles DMA interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void DMA0_Channel5_IRQHandler(void)
{
    if(dma_interrupt_flag_get(DMA0, DMA_CH5, DMA_INT_FTF) != RESET)
    {
        vUSART1ReceiveCallback();

        dma_interrupt_flag_clear(DMA0, DMA_CH5, DMA_INT_FTF);
    }
    else if(dma_interrupt_flag_get(DMA0, DMA_CH5, DMA_INT_HTF) != RESET)
    {
        vUSART1ReceiveCallback();

        dma_interrupt_flag_clear(DMA0, DMA_CH5, DMA_INT_HTF);
    }
}

/*!
    \brief      this function handles USART interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void USART2_IRQHandler(void)
{
    volatile static uint32_t uiMDANdtrNow = 0, uiMDANdtrOld = 0;

    if(usart_interrupt_flag_get(USART2, USART_INT_FLAG_IDLE) != RESET)
    {
        vUSART2ReceiveCallback();

        /* 软件先读USART_STAT0，再读USART_DATA可清除空闲中断标志 */
        usart_data_receive(USART2);
        usart_interrupt_flag_clear(USART2, USART_INT_FLAG_IDLE);

        /* 开启串口接收中断，用以判断通信通道是否繁忙 */
        usart_interrupt_enable(USART2, USART_INT_RBNE);
    }
    else if(usart_flag_get(USART2, USART_FLAG_ORERR) != RESET)
    {
        /* 软件先读USART_STAT0，再读USART_DATA可清除错误中断标志 */
        usart_data_receive(USART2);

        /* 重新初始化 */
        vUart2Init();
    }
    /* 错误中断 */
    else if((usart_flag_get(USART2, USART_FLAG_NERR) != RESET) ||
            (usart_flag_get(USART2, USART_FLAG_FERR) != RESET) ||
            (usart_flag_get(USART2, USART_FLAG_PERR) != RESET))
    {
        usart_flag_clear(USART2, USART_FLAG_CTS);
        usart_flag_clear(USART2, USART_FLAG_LBD);
        usart_flag_clear(USART2, USART_FLAG_TC);
        usart_flag_clear(USART2, USART_FLAG_RBNE);
        usart_flag_clear(USART2, USART_FLAG_EB);
        usart_flag_clear(USART2, USART_FLAG_RT);

        usart_interrupt_flag_clear(USART2, USART_INT_FLAG_CTS);
        usart_interrupt_flag_clear(USART2, USART_INT_FLAG_LBD);
        usart_interrupt_flag_clear(USART2, USART_INT_FLAG_RBNE);
        usart_interrupt_flag_clear(USART2, USART_INT_FLAG_EB);
        usart_interrupt_flag_clear(USART2, USART_INT_FLAG_RT);

        /* 软件先读USART_STAT0，再读USART_DATA可清除错误xxx中断标志 */
        usart_data_receive(USART2);
    }
}

/*!
    \brief      this function handles DMA interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void DMA0_Channel2_IRQHandler(void)
{
    if(dma_interrupt_flag_get(DMA0, DMA_CH2, DMA_INT_FTF) != RESET)
    {
        vUSART2ReceiveCallback();

        dma_interrupt_flag_clear(DMA0, DMA_CH2, DMA_INT_FTF);
    }
    else if(dma_interrupt_flag_get(DMA0, DMA_CH2, DMA_INT_HTF) != RESET)
    {
        vUSART2ReceiveCallback();

        dma_interrupt_flag_clear(DMA0, DMA_CH2, DMA_INT_HTF);
    }
}

/*!
    \brief      this function handles USART interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void UART3_IRQHandler(void)
{
    volatile static uint32_t uiMDANdtrNow = 0, uiMDANdtrOld = 0;

    if(usart_interrupt_flag_get(UART3, USART_INT_FLAG_IDLE) != RESET)
    {
        vUSART3ReceiveCallback();

        /* 软件先读USART_STAT0，再读USART_DATA可清除空闲中断标志 */
        usart_data_receive(UART3);
        usart_interrupt_flag_clear(UART3, USART_INT_FLAG_IDLE);

//        /* 给出信号量，以启动任务执行解析 */
//        xTaskNotifyFromISR(g_TaskMessageSlaveHand, 0x08, eSetBits, NULL);
    }
    else if(usart_flag_get(UART3, USART_FLAG_ORERR) != RESET)
    {
        /* 软件先读USART_STAT0，再读USART_DATA可清除错误中断标志 */
        usart_data_receive(UART3);

        /* 重新初始化 */
        vUart3Init();
    }
    /* 错误中断 */
    else if((usart_flag_get(UART3, USART_FLAG_NERR) != RESET) ||
            (usart_flag_get(UART3, USART_FLAG_FERR) != RESET) ||
            (usart_flag_get(UART3, USART_FLAG_PERR) != RESET))
    {
        usart_flag_clear(UART3, USART_FLAG_CTS);
        usart_flag_clear(UART3, USART_FLAG_LBD);
        usart_flag_clear(UART3, USART_FLAG_TC);
        usart_flag_clear(UART3, USART_FLAG_RBNE);
        usart_flag_clear(UART3, USART_FLAG_EB);
        usart_flag_clear(UART3, USART_FLAG_RT);

        usart_interrupt_flag_clear(UART3, USART_INT_FLAG_CTS);
        usart_interrupt_flag_clear(UART3, USART_INT_FLAG_LBD);
        usart_interrupt_flag_clear(UART3, USART_INT_FLAG_TC);
        usart_interrupt_flag_clear(UART3, USART_INT_FLAG_RBNE);
        usart_interrupt_flag_clear(UART3, USART_INT_FLAG_EB);
        usart_interrupt_flag_clear(UART3, USART_INT_FLAG_RT);

        /* 软件先读USART_STAT0，再读USART_DATA可清除xxx中断标志 */
        usart_data_receive(UART3);
    }
}

/*!
    \brief      this function handles DMA interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void DMA1_Channel2_IRQHandler(void)
{
    if(dma_interrupt_flag_get(DMA1, DMA_CH2, DMA_INT_FTF) != RESET)
    {
        vUSART3ReceiveCallback();

        dma_interrupt_flag_clear(DMA1, DMA_CH2, DMA_INT_FTF);
    }
    else if(dma_interrupt_flag_get(DMA1, DMA_CH2, DMA_INT_HTF) != RESET)
    {
        vUSART3ReceiveCallback();

        dma_interrupt_flag_clear(DMA1, DMA_CH2, DMA_INT_HTF);
    }
}

/*!
    \brief      this function handles CAN0 RX0 exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void USBD_LP_CAN0_RX0_IRQHandler(void)
{
//    usbd_isr();
}

/*!
    \brief      this function handles CAN0 RX0 exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void CAN0_RX1_IRQHandler(void)
{
    can_receive_message_struct receive_message = {0};

    while(can_interrupt_flag_get(CAN0, CAN_INT_FLAG_RFL1) != RESET)
    {
        /* receive message（读取1次FIFO数据后，硬件会自动清除 CAN_INT_FLAG_RFL0 中断标志） */
        can_message_receive(CAN0, CAN_FIFO1, &receive_message);
    }
}

/*!
    \brief      This function handles TIMER interrupt request.
    \param[in]  none
    \param[out] none
    \retval     none
*/
void TIMER5_IRQHandler(void)
{
    if(timer_interrupt_flag_get(TIMER5, TIMER_INT_UP) != RESET)
    {
        timer_interrupt_flag_clear(TIMER5, TIMER_INT_UP);

        /* 溢出值为65536 */
        g_lTimeBase += 65536ll;
    }
}

/*!
    \brief      this function handles RTC global interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void RTC_IRQHandler(void)
{
    if (rtc_flag_get(RTC_FLAG_SECOND) != RESET)
    {
        /* clear the RTC second interrupt flag*/
        rtc_flag_clear(RTC_FLAG_SECOND);
    }

    if (rtc_flag_get(RTC_FLAG_ALARM) != RESET)
    {
        /* clear the RTC second interrupt flag*/
        rtc_flag_clear(RTC_FLAG_ALARM);
    }
}

/*!
    \brief      this function handles RTC global interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void RTC_Alarm_IRQHandler(void)
{
    if (rtc_flag_get(RTC_FLAG_ALARM) != RESET)
    {
        /* clear the RTC second interrupt flag*/
        rtc_flag_clear(RTC_FLAG_ALARM);
    }
}
